<template>
  <div :style="{ backgroundColor: bgColor }" class="k-tabbar">
    <div v-if="showLine" class="k-tabbar-line"></div>
    <div class="k-tabbar-box">
      <div @click="itemClick(index)" :style="{ width: 100 / list.length + '%' }" :key="JSON.stringify(item)"
        v-for="(item, index) in list" class="k-tabbar-one">
        <img :class="{'k-tabbar-image':true,'k-transition':transition?current==index:false}" :width="imageSize[0]"
          :height="imageSize[1]" :src="current == index? item.src1:item.src2" />
        <div :style="{
            marginTop: space + 'px',
            fontSize: fontSize + 'px',
            transition: transition ? 'color 0.2s' : 'none',
            color: current == index ? selectedColor : color,
          }" class="k-tabbar-text">
          {{ item.text }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "k-tabbar",
    data() {
      return {
        //索引
        current: 0,
      };
    },
    methods: {
      //item被点击
      itemClick(index) {

        if (this.current == index) return
        //跳转路由
        this.$router.replace({
          path: this.list[index].route,
        });

        //发射事件传递给父组件
        this.$emit("change", index);
        this.current = index;
      },
    },
    //组件挂载完成
    mounted() {
      //初始化选择索引
      this.current = this.index;
    },
    props: {
      //tab导航的数据列表，包括tab选择图标，未选择图标，文本内容，以及路由
      list: {
        type: Array,
        required: true,
      },
      //初始选择的索引
      index: {
        type: Number,
        default: 0,
      },
      //tab的背景色
      bgColor: {
        type: String,
        default: "white",
      },
      //文字选中时的颜色
      selectedColor: {
        type: String,
        default: "black",
      },
      //文字未选择时的颜色
      color: {
        type: String,
        default: "rgba(0,0,0,0.5)",
      },
      //图标和文字之间的间隔，单位px
      space: {
        type: Number,
        default: 4,
      },
      //是否显示线条
      showLine: {
        type: Boolean,
        default: true,
      },
      //切换是否使用过渡
      transition: {
        type: Boolean,
        default: true,
      },
      //图片宽高,单位px
      imageSize: {
        type: Array,
        default () {
          return [28, 28];
        },
      },
      //字体大小,单位px
      fontSize: {
        type: Number,
        default: 14,
      },
    },
  };
</script>

<style src='./tabbar.css' scoped></style>
